<template>
  <q-page class="cc-admin">
    <div class="col bg-white shadow-2 q-pa-md q-ma-sm">
      <q-table flat color="primary" class="cross_table" separator="cell" :columns="columns" :data="list" row-key="id" :pagination.sync="pagination" :visible-columns="group" @request="query" :rows-per-page-options="[10, 20, 50, 100]" selection="multiple" :selected.sync="selected">
        <template v-slot:top="">
          <div class="row no-wrap full-width">
            <q-input clearable outlined dense placeholder="请输入关键字搜索" class="on-left" @input="query" debounce="500" v-model="key">
              <template #append>
                <q-btn flat round icon="search" color="primary" @click="query" :loading="loading">
                  <q-tooltip>搜索</q-tooltip>
                </q-btn>
              </template>
            </q-input>
            <q-space />

            <div class="q-gutter-xs" style="margin-left: 10px">
              <q-btn icon="add" no-wrap color="primary" label="创建卷子" @click="add" />
            </div>
          </div>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <q-btn flat round dense color="primary" icon="edit" @click="edit(props.row)"> <q-tooltip>编辑</q-tooltip></q-btn>
            <!-- <q-btn flat round dense color="primary" icon="mdi-content-copy" @click="copy(props.row)">
              <q-tooltip>复制</q-tooltip>
            </q-btn> -->
            <q-btn flat round dense color="primary" icon="mdi-file-search-outline" @click="ViewExamPaper(props.row)">
              <q-tooltip>查看</q-tooltip>
            </q-btn>
            <btn-del label="试卷" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <q-dialog maximized flat persistent ref="dialog">
      <q-form @submit="submit" class="dialog_card column">
        <h5 class="view_title justify-between q-px-md">
          {{ editType }}试卷
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <q-scroll-area class="col">
          <div class="row items-start q-col-gutter-x-md dialog_form q-pa-md">
            <div class="col-12">
              <h5>试卷名称:</h5>
              <q-input outlined dense v-model="form.paperName" type="text" />
            </div>
            <div class="col-12">
              <h5>请选择不同类型题目百分比:</h5>
            </div>
            <!-- <div v-for="(item, index) in categoryOptions" :key="index">
              <h5>{{ item.label }}:</h5>
              <q-input outlined dense v-model="form.percent[index]" type="text" />
            </div> -->
            <div class="q-gutter-y-md" style="max-width: 1000px">
              <q-card>
                <q-tabs v-model="tab" dense class="text-grey" active-color="primary" indicator-color="primary" align="justify" narrow-indicator>
                  <q-tab :name="item.value" :label="item.label" v-for="(item, index) in tabOptions" :key="item.value" @click="logTab(item.value, index)" />
                </q-tabs>
                <q-separator />
                <div style="display: flex; flex-direction: row">
                  <q-tab-panels v-model="tab" animated>
                    <q-tab-panel :name="item.tab" v-for="item in categoryOptions[tab]" :key="item.value">
                      <h5>该科选择题目总数:</h5>
                      <q-input outlined dense v-model="form.quantity[index]" type="text" />
                      <div v-for="(item, index) in categoryOptions[tab]" :key="item.value">
                        <h5>{{ item.label }}:</h5>
                        <q-input outlined dense v-model="form.percent[tab].percentArr[index]" type="text" />
                      </div>
                    </q-tab-panel>
                  </q-tab-panels>
                  <q-tab-panels v-model="tab" animated>
                    <q-tab-panel :name="item.tab" v-for="item in categoryOptions[tab]" :key="item.value">
                      <h5>该科应用题目总数:</h5>
                      <q-input outlined dense v-model="form.designQuantity[index]" type="text" />
                      <div v-for="(item, index) in categoryOptions[tab]" :key="item.value">
                        <h5>{{ item.label }}:</h5>
                        <q-input outlined dense v-model="form.designPercent[tab].percentArr[index]" type="text" />
                      </div>
                    </q-tab-panel>
                  </q-tab-panels>
                </div>
              </q-card>
            </div>
            <q-toggle class="row justify-start " left-label label="是否要从错题中抽题" false-value="2" true-value="1" v-model="form.needError" />
          </div>
        </q-scroll-area>
        <div class="row justify-center q-pa-md">
          <q-btn outline color="primary" icon="mdi-close-thick" label="关闭" v-close-popup />
          <q-btn class="q-mx-md" color="primary" icon="mdi-check-bold" label="提交" :loading="loading" type="submit" />
        </div>
      </q-form>
    </q-dialog>
    <q-dialog maximized flat persistent ref="examDialog">
      <q-form @submit="submit2" class="dialog_card column">
        <h5 class="view_title justify-between q-px-md">
          查看试卷
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <q-scroll-area class="col">
          <div class="row q-col-gutter-x-md dialog_form q-pa-md">
            <div class="col-12">
              <h5>一、选择题</h5>
              <!-- <q-input outlined dense v-model="" type="text" /> -->
            </div>
            <div class="col-12 q-pb-md" v-for="(item, index) in this.examForm.choiceQuestionsList" :key="item.id">
              <div>{{ index + 1 + '.' + item.question }}</div>
              <div class="q-video" style="margin-top: 10px" v-if="item.viedoUrl">
                <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :image="item.viedoUrl" v-if="item.viedoUrl" @inited="inited">
                  <img class="q-pl-sm" :src="item.viedoUrl" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                </viewer>
              </div>
              <q-radio v-model="examForm.choiceAnswer[index]" color="cyan" :label="'A: ' + item.optionA" val="A" @input="changeCheck({ value: 'A', index })" />
              <q-radio v-model="examForm.choiceAnswer[index]" color="cyan" :label="'B: ' + item.optionB" val="B" @input="changeCheck({ value: 'B', index })" />
              <q-radio v-model="examForm.choiceAnswer[index]" color="cyan" :label="'C: ' + item.optionC" val="C" @input="changeCheck({ value: 'C', index })" />
              <q-radio v-model="examForm.choiceAnswer[index]" color="cyan" :label="'D: ' + item.optionD" val="D" @input="changeCheck({ value: 'D', index })" />

            </div>
            <div class="col-12">
              <h6>二、应用题</h6>
              <!-- <q-input outlined dense v-model="" type="text" /> -->
            </div>
            <div class="col-12 q-pb-md q-mb-xl" style="" v-for="(item, index2) in this.examForm.designQuestionsListDtoList" :key="item.id">
              <div style="font-weight: 800; font-size: 16px">{{ index2 + 1 + '.' + item.questionStem }}</div>
              <div class="q-video" style="margin-top: 10px" v-if="item.viedoUrl">
                <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :image="item.viedoUrl" v-if="item.viedoUrl" @inited="inited">
                  <img class="q-pl-sm" :src="item.viedoUrl" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                </viewer>
              </div>
              <div class="col-12" style="height: 100%; border: 1px solid black">
                <q-splitter v-model="splitterModel">
                  <template v-slot:before>
                    <q-tabs v-model="tab2[index]" vertical class="text-teal">
                      <q-tab :name="item2.indexNum + item2.question" icon="" :label="`第${index + 1}题`" v-for="(item2, index) in item.questionList" :key="item2.id" />
                    </q-tabs>
                  </template>

                  <template v-slot:after>
                    <q-tab-panels v-model="tab2[index]" animated swipeable vertical transition-prev="jump-up" transition-next="jump-up">
                      <q-tab-panel :name="item3.indexNum + item3.question" v-for="(item3, index) in item.questionList" :key="item3.id">
                        <div>
                          <div class="col-12">
                            <h5>题目：</h5>
                            <q-input outlined readonly dense v-model="item3.question" type="textarea" />
                          </div>
                          <div class="col-12">
                            <h5>答案：</h5>
                            <!--                                                    大题索引  小题索引 -->
                            <q-input outlined dense v-model="examForm.designAnswer[index2][index].answer" type="textarea" @input="log" :rows="15" />
                          </div>
                          <div class="col-12" v-if="!item3.viedoUrl">
                            <h5>文件上传：</h5>
                            <q-uploader url="http://127.0.0.1:9008/weather-api/upload" :headers="headers" field-name="uploadFile" label="文件上传" @uploaded="uploadResult" color="purple" square flat bordered style="max-width: 300px" @added="startUpload(index2, index)" />
                          </div>
                          <div class="q-pa-md" style="display: flex;align-items: center">
                            <viewer class="label-list q-mb-sm " style="max-height: 100px" ref="viewer" :options="options" :image="item3.viedoUrl" v-if="item3.viedoUrl" @inited="inited">
                              <img class="q-pl-sm" :src="item3.viedoUrl" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                            </viewer>
                            <div class="col-12" style="margin-top: 10px">
                              <q-btn color="primary" icon="mdi-delete" label="删除" outline class="q-mx-md" @click="delVideo" v-if="item3.viedoUrl" />
                            </div>
                          </div>
                        </div>
                      </q-tab-panel>
                    </q-tab-panels>
                  </template>
                </q-splitter>
              </div>
              <!-- 答案解析条件需要改为作答完毕 -->
              <h5 v-if="editType === '答题'" class="text-red-6">{{ item.analysis }}</h5>
            </div>
          </div>
        </q-scroll-area>
        <div class="row justify-center q-pa-md">
          <q-btn outline color="primary" icon="mdi-close-thick" label="关闭" v-close-popup />
          <q-btn class="q-mx-md" color="primary" icon="mdi-check-bold" label="提交" :loading="loading" type="submit2" />
        </div>
      </q-form>
    </q-dialog>
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import Viewer from 'viewerjs';

export default {
  name: 'ExamPaper',
  mixins: [IndexMixin],
  components: {
    confirm,
  },
  data() {
    return {
      catalog: '01',
      tab: '0101',
      tab2: [],
      options: {
        title: false,
      },
      index: 0,
      index2: 0,
      splitterModel: 20,
      form: {
        subjectId: '01',
        subjectText: '计算机',
        paperName: '',
        quantity: [10, 10, 10, 10], // 每道题的总数
        designQuantity: [1, 1, 1, 1], // 每种应用题的总数
        needError: '2',
        percent: {
          '0101': {
            tab: '0101',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0102': {
            tab: '0102',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0103': {
            tab: '0103',
            percentArr: [0, 0, 0, 0, 0],
          },
          '0104': {
            tab: '0104',
            percentArr: [0, 0, 0, 0, 0, 0],
          },
        },
        designPercent: {
          '0101': {
            tab: '0101',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0102': {
            tab: '0102',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0103': {
            tab: '0103',
            percentArr: [0, 0, 0, 0, 0],
          },
          '0104': {
            tab: '0104',
            percentArr: [0, 0, 0, 0, 0, 0],
          },
        },
      },
      emptyForm: {
        subjectId: '01',
        subjectText: '计算机',
        paperName: '',
        quantity: [10, 10, 10, 10], // 每道题的总数
        designQuantity: [1, 1, 1, 1], // 每种应用题的总数
        needError: '2',
        percent: {
          '0101': {
            tab: '0101',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0102': {
            tab: '0102',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0103': {
            tab: '0103',
            percentArr: [0, 0, 0, 0, 0],
          },
          '0104': {
            tab: '0104',
            percentArr: [0, 0, 0, 0, 0, 0],
          },
        },
        designPercent: {
          '0101': {
            tab: '0101',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0102': {
            tab: '0102',
            percentArr: [0, 0, 0, 0, 0, 0, 0],
          },
          '0103': {
            tab: '0103',
            percentArr: [0, 0, 0, 0, 0],
          },
          '0104': {
            tab: '0104',
            percentArr: [0, 0, 0, 0, 0, 0],
          },
        },
      },
      tabOptions: [
        { label: '数据结构', value: '0101' },
        { label: '计算机组成原理', value: '0102' },
        { label: '操作系统', value: '0103' },
        { label: '计算机网络', value: '0104' },
      ],
      categoryOptions: {
        '0101': [
          { label: '线性表', value: '1', tab: '0101' },
          { label: '栈和队列', value: '2', tab: '0101' },
          { label: '串', value: '3', tab: '0101' },
          { label: '树与二叉树', value: '4', tab: '0101' },
          { label: '图', value: '5', tab: '0101' },
          { label: '查找', value: '6', tab: '0101' },
          { label: '排序', value: '7', tab: '0101' },
        ],
        '0102': [
          { label: '计算机系统概述', value: '1', tab: '0102' },
          { label: '数据的表示和运算', value: '2', tab: '0102' },
          { label: '存储器层次结构', value: '3', tab: '0102' },
          { label: '指令系统', value: '4', tab: '0102' },
          { label: '中央处理器（CPU）', value: '5', tab: '0102' },
          { label: '总线', value: '6', tab: '0102' },
          { label: '输入输出系统', value: '7', tab: '0102' },
        ],
        '0103': [
          { label: '操作系统概述', value: '1', tab: '0103' },
          { label: '进程管理', value: '2', tab: '0103' },
          { label: '内存管理', value: '3', tab: '0103' },
          { label: '文件管理', value: '4', tab: '0103' },
          { label: '设备管理', value: '5', tab: '0103' },
        ],
        '0104': [
          { label: '计算机网络体系结构', value: '1', tab: '0104' },
          { label: '物理层', value: '2', tab: '0104' },
          { label: '数据链路层', value: '3', tab: '0104' },
          { label: '网络层', value: '4', tab: '0104' },
          { label: '传输层', value: '5', tab: '0104' },
          { label: '应用层', value: '6', tab: '0104' },
        ],
      },
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
        },
        {
          name: 'paperName',
          align: 'center',
          label: '试卷名称',
          field: 'paperName',
        },
        {
          name: 'opt',
          align: 'center',
          label: '操作',
          field: 'id',
        },
      ],
      examForm: {
        id: '',
        subjectId: '01',
        subjectText: '计算机',
        choiceIds: '',
        paperName: '',
        designQuestionsListDtoList: [],
        designAnswer: [],
        choiceQuestionsList: [],
        choiceAnswer: [],
      },
      showQuery: true,
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/upload`,
      imgUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/static`,
      url: {
        list: '/exam/paper/list',
        add: '/exam/paper/add',
        edit: '/exam/paper/edit',
        copy: '/exam/paper/copy',
        delete: '/exam/paper/delete',
        deleteBatch: '/exam/paper/deleteBatch',
        exportXlsUrl: '/exam/paper/exportXls',
        importExcelUrl: '/exam/paper/importExcel',
        examAdd: '/exam/paper/examAdd',
      },
    };
  },
  methods: {
    // 初始化预览组件
    inited(viewer) {
      this.$viewer = viewer;
    },
    startUpload(index2, index) {
      console.log(index2, index);
      this.index = index;
      this.index2 = index2;
    },
    log() {
      // console.log(this.examForm.designAnswer);
    },
    changeCheck({ value, index }) {
      this.examForm.choiceAnswer[index] = value;
    },
    reset() {
      this.tab = '0101';
      this.form = JSON.parse(JSON.stringify(this.emptyForm));
    },
    logTab(value, index) {
      this.tab = value;
      this.index = index;
    },
    getDictLabel,
    initDict() { },

    ViewExamPaper(row) {
      this.$axios
        .post(`${process.env.SERVER_URL}${process.env.BASE_URL}/exam/paper/getexampaper`, {
          id: row.id,
        })
        .then((result) => {
          // this.$info(r);
          this.examForm.designQuestionsListDtoList = result.result.designQuestionsListDtoList;
          this.examForm.choiceQuestionsList = result.result.choiceQuestionsList;
          this.examForm.designAnswer = result.result.designQuestionsListDtoList;
          this.examForm.id = result.result.id;
          this.examForm.paperName = result.result.paperName;
          this.examForm.choiceIds = result.result.choiceIds;
          // examForm.designAnswer.push({...result.result.designQuestionsListDtoList.questionList})
          for (let i = 0; i < result.result.designQuestionsListDtoList.length; i++) {
            for (let j = 0; j < result.result.designQuestionsListDtoList[i].questionList.length; j++) {
              // result.result.designQuestionsListDtoList[i].questionList[j].answer = '';
              this.examForm.designAnswer[i][j] = result.result.designQuestionsListDtoList[i].questionList[j];
              this.examForm.designAnswer[i][j].realAnswer = this.examForm.designAnswer[i][j].answer;
              this.examForm.designAnswer[i][j].answer = '';
              this.examForm.designAnswer[i][j].analysisVideo = this.examForm.designAnswer[i][j].viedoUrl;
              this.examForm.designAnswer[i][j].viedoUrl = '';
            }
          }
          // 为每个对象添加 index 字段
          this.examForm.designAnswer = this.examForm.designAnswer.map((item, index) => ({
            ...item, // 保留原有属性
            indexNum: index + 1, // 添加 index 字段（从 1 开始）
          }));
        });
      this.editType = '答题';
      this.$refs.examDialog.show();
    },
    submit2() {
      this.examForm.type = '已完成';
      this.$axios
        .post(this.url.examAdd, this.examForm)
        .then((r) => {
          this.$info(r.message);
          this.$refs.examDialog.hide();
        })
        .finally(() => {
          this.query();
        });
    },
    uploadResult(info) {
      const fileResult = JSON.parse(info.xhr.response);
      this.fileResult = fileResult;
      this.examForm.designAnswer[this.index2].questionList[this.index].viedoUrl = `http://127.0.0.1:9000${fileResult.url}`;
      console.log(this.examForm);

      this.showVideo = true;
    },
    delVideo() {
      this.$axios
        .post(`${process.env.SERVER_URL}${process.env.BASE_URL}/deleteVideo`, {
          url: this.examForm.designAnswer[this.index2].questionList[this.index].viedoUrl,
        })
        .then((r) => {
          this.$info(r.module);
          this.examForm.designAnswer[this.index2].questionList[this.index].viedoUrl = '';
        });
    },
  },
  mounted() {
    this.initDict();
  },
};
</script>

<style lang="stylus">
.answerdiv
  white-space normal
  word-wrap break-word
  overflow-wrap break-word
  display inline-block
  .answer
    display inline-flex
    max-width 500px
</style>
